import { MessageRequest, useMessage } from '@/hooks/tools/useMessage';
import {
  AccessTime as AccessTimeIcon,
  ExpandMore as ExpandMoreIcon,
  FavoriteBorder as FavoriteBorderIcon,
  Favorite as FavoriteIcon,
  Launch as LaunchIcon,
  Person as PersonIcon,
  Reply as ReplyIcon,
  Send as SendIcon
} from '@mui/icons-material';
import {
  Alert,
  Avatar,
  Box,
  Button,
  Card,
  CardContent,
  CircularProgress,
  IconButton,
  Link,
  Snackbar,
  Stack,
  TextField,
  Tooltip,
  Typography,
  alpha
} from '@mui/material';
import { useCallback, useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';

interface MessagePanelProps {
  onClose: () => void;
}

const MessagePanel = ({ onClose }: MessagePanelProps) => {
  const navigate = useNavigate();
  const {
    messages,
    loading,
    error,
    total,
    submitting,
    getPublicMessages,
    submitMessage,
    likeMessage,
    clearError
  } = useMessage();

  const [nickname, setNickname] = useState('');
  const [email, setEmail] = useState('');
  const [content, setContent] = useState('');
  const [showForm, setShowForm] = useState(false);
  const [snackbarOpen, setSnackbarOpen] = useState(false);
  const [snackbarMessage, setSnackbarMessage] = useState('');
  const [snackbarSeverity, setSnackbarSeverity] = useState<'success' | 'error'>('success');
  const [likedMessages, setLikedMessages] = useState<Set<number>>(new Set());
  const [displayCount, setDisplayCount] = useState(5);

  useEffect(() => {
    // 只加载最新的几条留言
    getPublicMessages(1, 10);
  }, [getPublicMessages]);

  const handleSubmit = useCallback(async (e: React.FormEvent) => {
    e.preventDefault();
    
    if (!nickname.trim() || !content.trim()) {
      showSnackbar('请填写昵称和留言内容', 'error');
      return;
    }

    try {
      const messageData: MessageRequest = {
        nickname: nickname.trim(),
        email: email.trim() || undefined,
        content: content.trim()
      };

      await submitMessage(messageData);
      
      // 清空表单
      setNickname('');
      setEmail('');
      setContent('');
      setShowForm(false);
      
      showSnackbar('留言提交成功，等待审核！', 'success');
      
      // 刷新留言列表
      setTimeout(() => {
        getPublicMessages(1, 10);
      }, 1000);
      
    } catch (err: any) {
      showSnackbar(err.message || '提交失败', 'error');
    }
  }, [nickname, content, email, submitMessage, getPublicMessages]);

  const handleLike = useCallback(async (messageId: number) => {
    if (likedMessages.has(messageId)) {
      showSnackbar('您已经点过赞了', 'error');
      return;
    }

    try {
      await likeMessage(messageId);
      setLikedMessages(prev => new Set([...prev, messageId]));
      showSnackbar('点赞成功！', 'success');
    } catch (err: any) {
      showSnackbar(err.message || '点赞失败', 'error');
    }
  }, [likeMessage, likedMessages]);

  const showSnackbar = useCallback((message: string, severity: 'success' | 'error') => {
    setSnackbarMessage(message);
    setSnackbarSeverity(severity);
    setSnackbarOpen(true);
  }, []);

  const handleCloseSnackbar = useCallback(() => {
    setSnackbarOpen(false);
  }, []);

  const getRandomAvatarColor = useCallback((nickname: string) => {
    const colors = ['#FF9C6E', '#6B73FF', '#52C41A', '#FFA940', '#FF85C0', '#40A9FF', '#95DE64'];
    let hash = 0;
    for (let i = 0; i < nickname.length; i++) {
      hash = nickname.charCodeAt(i) + ((hash << 5) - hash);
    }
    return colors[Math.abs(hash) % colors.length];
  }, []);

  const handleViewMore = useCallback(() => {
    onClose();
    navigate('/tools/messageboard');
  }, [onClose, navigate]);

  const displayedMessages = messages.slice(0, displayCount);

  return (
    <Box sx={{ height: '100%', display: 'flex', flexDirection: 'column' }}>
      {/* 快速操作区 */}
      <Box sx={{ p: 2, borderBottom: '1px solid', borderColor: 'divider' }}>
        <Stack direction="row" spacing={1} justifyContent="center">
          <Button
            variant={showForm ? 'contained' : 'outlined'}
            size="small"
            startIcon={<SendIcon />}
            onClick={() => setShowForm(!showForm)}
            sx={{
              borderRadius: '20px',
              px: 2,
              bgcolor: showForm ? '#FF85C0' : 'transparent',
              borderColor: '#FF85C0',
              color: showForm ? '#fff' : '#FF85C0',
              '&:hover': {
                bgcolor: showForm ? '#FF6BB3' : alpha('#FF85C0', 0.1)
              }
            }}
          >
            {showForm ? '收起' : '写留言'}
          </Button>
          <Button
            variant="outlined"
            size="small"
            endIcon={<LaunchIcon />}
            onClick={handleViewMore}
            sx={{
              borderRadius: '20px',
              px: 2,
              borderColor: '#6B73FF',
              color: '#6B73FF',
              '&:hover': {
                bgcolor: alpha('#6B73FF', 0.1)
              }
            }}
          >
            查看全部
          </Button>
        </Stack>
      </Box>

      {/* 留言提交表单 */}
      {showForm && (
        <Box sx={{ p: 2, borderBottom: '1px solid', borderColor: 'divider' }}>
          <Box component="form" onSubmit={handleSubmit}>
            <Stack spacing={2}>
              <TextField
                size="small"
                label="昵称 *"
                value={nickname}
                onChange={(e) => setNickname(e.target.value)}
                placeholder="请输入您的昵称"
                required
                sx={{
                  '& .MuiOutlinedInput-root': {
                    borderRadius: '12px'
                  }
                }}
              />
              <TextField
                size="small"
                label="邮箱"
                type="email"
                value={email}
                onChange={(e) => setEmail(e.target.value)}
                placeholder="请输入您的邮箱（可选）"
                sx={{
                  '& .MuiOutlinedInput-root': {
                    borderRadius: '12px'
                  }
                }}
              />
              <TextField
                multiline
                rows={3}
                size="small"
                label="留言内容 *"
                value={content}
                onChange={(e) => setContent(e.target.value)}
                placeholder="请输入您的留言内容..."
                required
                inputProps={{ maxLength: 500 }}
                helperText={`${content.length}/500`}
                sx={{
                  '& .MuiOutlinedInput-root': {
                    borderRadius: '12px'
                  }
                }}
              />
              <Button
                type="submit"
                variant="contained"
                startIcon={<SendIcon />}
                disabled={submitting || !nickname.trim() || !content.trim()}
                sx={{
                  borderRadius: '20px',
                  background: 'linear-gradient(135deg, #FF85C0 0%, #FFADD6 100%)',
                  '&:hover': {
                    background: 'linear-gradient(135deg, #FF6BB3 0%, #FF85C0 100%)',
                  }
                }}
              >
                {submitting ? '提交中...' : '发表留言'}
              </Button>
            </Stack>
          </Box>
        </Box>
      )}

      {/* 留言列表 */}
      <Box sx={{ flex: 1, overflow: 'auto', p: 1 }}>
        {loading ? (
          <Box sx={{ display: 'flex', justifyContent: 'center', p: 4 }}>
            <CircularProgress size={32} sx={{ color: '#FF85C0' }} />
          </Box>
        ) : displayedMessages.length === 0 ? (
          <Box sx={{ textAlign: 'center', p: 4 }}>
            <Typography color="text.secondary" variant="body2">
              暂无留言，快来发表第一条留言吧！
            </Typography>
          </Box>
        ) : (
          <Stack spacing={1}>
            {displayedMessages.map((message) => (
              <Card 
                key={message.id}
                elevation={0}
                sx={{ 
                  borderRadius: 2,
                  border: '1px solid',
                  borderColor: 'divider',
                  background: message.isTop 
                    ? 'linear-gradient(135deg, #FFF9E6 0%, #FFFBF0 100%)'
                    : 'transparent'
                }}
              >
                <CardContent sx={{ p: 2, '&:last-child': { pb: 2 } }}>
                  <Stack spacing={1}>
                    {/* 用户信息 */}
                    <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                      <Avatar 
                        sx={{ 
                          bgcolor: getRandomAvatarColor(message.nickname),
                          width: 32,
                          height: 32
                        }}
                      >
                        <PersonIcon sx={{ fontSize: 18 }} />
                      </Avatar>
                      <Box sx={{ flex: 1, minWidth: 0 }}>
                        <Typography variant="subtitle2" sx={{ fontWeight: 600, fontSize: '0.875rem' }}>
                          {message.nickname}
                        </Typography>
                        <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.5 }}>
                          <AccessTimeIcon sx={{ fontSize: 12, color: 'text.secondary' }} />
                          <Typography variant="caption" color="text.secondary">
                            {message.createTimeDisplay}
                          </Typography>
                        </Box>
                      </Box>
                      <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.5 }}>
                        <Tooltip title="点赞">
                          <IconButton 
                            size="small"
                            onClick={() => handleLike(message.id)}
                            disabled={likedMessages.has(message.id)}
                            color={likedMessages.has(message.id) ? 'error' : 'default'}
                          >
                            {likedMessages.has(message.id) ? 
                              <FavoriteIcon sx={{ fontSize: 16 }} /> : 
                              <FavoriteBorderIcon sx={{ fontSize: 16 }} />
                            }
                          </IconButton>
                        </Tooltip>
                        <Typography variant="caption" color="text.secondary">
                          {message.likeCount}
                        </Typography>
                      </Box>
                    </Box>

                    {/* 留言内容 */}
                    <Typography 
                      variant="body2" 
                      sx={{ 
                        lineHeight: 1.5,
                        whiteSpace: 'pre-wrap',
                        wordBreak: 'break-word',
                        fontSize: '0.875rem'
                      }}
                    >
                      {message.content}
                    </Typography>

                    {/* 管理员回复 */}
                    {message.reply && (
                      <Box 
                        sx={{ 
                          mt: 1,
                          p: 1.5,
                          bgcolor: alpha('#6B73FF', 0.05),
                          borderRadius: 1,
                          borderLeft: '3px solid #6B73FF'
                        }}
                      >
                        <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.5, mb: 0.5 }}>
                          <ReplyIcon sx={{ fontSize: 14, color: '#6B73FF' }} />
                          <Typography variant="caption" sx={{ fontWeight: 600, color: '#6B73FF' }}>
                            管理员回复
                          </Typography>
                        </Box>
                        <Typography 
                          variant="caption" 
                          sx={{ 
                            lineHeight: 1.4,
                            whiteSpace: 'pre-wrap',
                            display: 'block'
                          }}
                        >
                          {message.reply}
                        </Typography>
                      </Box>
                    )}
                  </Stack>
                </CardContent>
              </Card>
            ))}

            {/* 加载更多按钮 */}
            {messages.length > displayCount && (
              <Box sx={{ textAlign: 'center', p: 1 }}>
                <Button
                  size="small"
                  startIcon={<ExpandMoreIcon />}
                  onClick={() => setDisplayCount(prev => prev + 5)}
                  sx={{
                    color: '#FF85C0',
                    '&:hover': {
                      bgcolor: alpha('#FF85C0', 0.1)
                    }
                  }}
                >
                  加载更多 ({messages.length - displayCount} 条)
                </Button>
              </Box>
            )}

            {/* 查看全部链接 */}
            {total > messages.length && (
              <Box sx={{ textAlign: 'center', p: 2 }}>
                <Link
                  component="button"
                  variant="body2"
                  onClick={handleViewMore}
                  sx={{
                    color: '#6B73FF',
                    textDecoration: 'none',
                    '&:hover': {
                      textDecoration: 'underline'
                    }
                  }}
                >
                  查看全部 {total} 条留言 →
                </Link>
              </Box>
            )}
          </Stack>
        )}
      </Box>

      {/* 错误提示 */}
      <Snackbar
        open={!!error}
        autoHideDuration={6000}
        onClose={clearError}
        anchorOrigin={{ vertical: 'top', horizontal: 'center' }}
      >
        <Alert severity="error" onClose={clearError} sx={{ width: '100%' }}>
          {error}
        </Alert>
      </Snackbar>

      {/* 操作结果提示 */}
      <Snackbar
        open={snackbarOpen}
        autoHideDuration={3000}
        onClose={handleCloseSnackbar}
        anchorOrigin={{ vertical: 'bottom', horizontal: 'center' }}
      >
        <Alert severity={snackbarSeverity} sx={{ width: '100%' }}>
          {snackbarMessage}
        </Alert>
      </Snackbar>
    </Box>
  );
};

export default MessagePanel;